package org.agent.aigccore.basic.exception;

import lombok.Getter;
import lombok.Setter;
import org.agent.aigccore.utils.FormatUtil;

import java.util.Map;

/**
 * @author shihong.msh
 * @version BusinessException.java, v 0.1 2022年03月31日 12:30 下午 shihong.msh
 */
@Setter
@Getter
public class BusinessException extends RuntimeException {

    /**
     * serialVersionUID
     */
    private static final long serialVersionUID = -1728398605857940973L;

    /**
     * 异常错误代码
     */
    private ResultCode errorCode = ResultCode.UNKNOWN_ERROR;

    /**
     * 扩展字段
     */
    private Map<String, String> extInfo;

    // ~~~ 构造方法

    /**
     * 有参构造方法
     *
     * @param code 错误码
     */
    public BusinessException(ResultCode code) {
        super(code.getDesc());
        this.errorCode = code;
    }

    /**
     * 有参构造
     *
     * @param code         错误码
     * @param errorMessage 错误描述
     */
    public BusinessException(ResultCode code, String errorMessage) {
        super(errorMessage);
        this.errorCode = code;
    }

    /**
     * 有参构造
     *
     * @param code         错误码
     * @param errorMessage 错误描述
     * @param extInfo      扩展字段
     */
    public BusinessException(ResultCode code, String errorMessage, Map<String, String> extInfo) {
        this(code, format(errorMessage));
        this.extInfo = extInfo;
    }

    /**
     * 有参构造
     *
     * @param code 错误码
     */
    public BusinessException(ResultCode code, String errorMessage, Object... params) {
        this(code, format(errorMessage, params));
    }

    /**
     * 有参构造
     *
     * @param code  错误码
     * @param cause 异常
     */
    public BusinessException(ResultCode code, Throwable cause) {
        super(code.getDesc(), cause);
        this.errorCode = code;
    }

    /**
     * 有参构造
     *
     * @param code         错误码
     * @param errorMessage 错误描述
     * @param cause        异常
     */
    public BusinessException(ResultCode code, String errorMessage, Throwable cause) {
        super(errorMessage, cause);
        this.errorCode = code;
    }

    /**
     * 错误信息参数化格式化
     *
     * @param message 错误信息,如:<code>xxx{0},xxx{1}...</code>
     * @param params  错误格式化参数,数组length与message参数化个数相同, 如:<code>Object[]  object=new Object[]{"xxx","xxx"}</code>
     * @return message
     */
    private static String format(String message, Object... params) {
        if (params != null && params.length != 0) {
            return FormatUtil.format(message, params);
        }
        return message;

    }

    /**
     * @see Throwable#toString()
     */
    @Override
    public final String toString() {
        String s = getClass().getName();
        String message = getLocalizedMessage();
        return s + ": " + errorCode.getCode() + "[" + message + "]。";
    }
}